<?php
namespace app\common\model;

// use think\Model;

class Useseal extends \app\common\model\Base
{




    //系统支持自动写入创建和更新的时间戳字段
    protected $autoWriteTimestamp = true;

    //类型自动转换
    protected $type = [
        'id'    =>  'integer',           // 规则id,自增主键           
    ];


    //关联表user表1 : 1 
    public function user()
    {
        return $this->hasOne('User','user_id','apply_user_id');
    }

    //关联表user表1 : 1 
    public function equipment()
    {
        return $this->hasOne('Equipment','id','equipment_id');
    }

    //关联表user表1 : 1 
    public function seal()
    {
        return $this->hasOne('seal','id','seal_id');
    }



    //关联表 流程 表1 : 1 
    public function process()
    {
        return $this->hasOne('Process','id','process_id');
    }
    
    //关联表 附件 表1 : n 
    public function attachs()
    {
        // return $this->hasMany('Attach','id','id');
        return $this->belongsToMany('Attachment','useseal_attach','attach_id','useseal_id');
    }
    //关联表 审批 表1 : n 
    public function audits(){
        return $this->hasMany('useseal_audit','id','id');
    }

    //关联表 用章记录 表1 : n 
    public function logs(){
        return $this->hasMany('useseal_log','useseal_id','id');
    }


    // protected static function init()
    // {
    // }


    //数据完成 时间
    protected $auto = array('exp_time');
    protected $insert = array('code','apply_user_id','use_times'); 
    protected $update = [];  
    
    //数据完成
    protected function setCodeAttr($value,$data){
        return date('YmdHis').rand(1000,9999);
    }
    protected function setUseTimesAttr($value,$data){
        return 0;
    }

    // protected function setExpTimeAttr($value,$data){
    //     print_r($data);

    //     //$exp_time = date("Y-m-d",strtotime("+".($data['exp_time_day']-1)." day"));
    //     //return $exp_time;
    // }


    //获取器
    // protected function getExpTimeAttr($value,$data){

    //     return date('Y-m-d' ,$value );
    // }
    // 获取器
    public function getStatusTextAttr($value,&$data)
    {
        // $arr = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核'];
        $arr = [-2=>'删除',-1=>'驳回',0=>'保存草稿',1=>'等待审核',2=>'审核通过',3=>'使用中',4=>'已经完成',5=>'已过期'];

        if(  $data['status']<4   and   (strtotime($data['exp_time'])+24*3600 -time()) <=0 ){
            $this->where('id' , $data['id'] )->setField('status',5);
            $data['status'] = 5;
        }

        return $arr[$data['status']];
    }





    /**
     * 得到 流程信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getAudits($id=null)
    {
        
        if( !$id ){
            $pk = $this->pk;
            $id = $this->$pk ;
        }


        $model =  model('UsesealAudit');

        $rs = $model->where('id',$id)->order('step asc')->select();

        $arr = array();

        $tree = model('Role')->tree;
        foreach($rs as $k => $v){
            $p = array();
            foreach( $tree->getPos($v['role_id']) as $pv){
                $p[] = $pv['name'];
            }
            $v['place'] = implode( ' / ' , $p);
            $arr[$v['step']][] = $v;
        }
        unset($rs);
        $arr2  = array();
        foreach ($arr as $k => $v) {
            $arr2[] = $v;
        }

        return $arr2;
    }


    /**
     * 当提交申请时  创建审核流程数据
     * @param  [type] $process_id [description]
     * @return [type]             [description]
     */
    public function makeAuditData( $process_id ){
        $list = array();

        $id = $this->id; //用章申请id
        $process_id = $this->process_id;
        $status = -1 ; // [ -1=>'' , 0=>'审核中...' ,  1=>'通过' , 2=> '驳回'  ];

        foreach( $this->process->audits as $audit){
            $step = $audit->step;
            $role_id = $audit->role_id ;
            foreach ($audit->role->users as $user){
                $user_id =  $user->user_id;
                $list[] =  ['id'=>$id ,'step'=>$step,'user_id'=>$user_id ,'role_id'=>$role_id, 'status'=>$status, 'flag'=>0 ];
            }
        }
        //先删除 后 添加。
        model('useseal_audit')->where('id', $id )->delete();
        model('useseal_audit')->isUpdate(false)->saveAll($list);
        $this->checkAudit();//创建完 调用 流程处理   
    }

    /**
     * 流程处理     在提交申请后  和 审核人提交审核后 调用
     * @return [type] [description]
     */
    public function checkAudit( $id = null ){
        //申请id
        if( !$id ){$pk = $this->pk;$id = $this->$pk ;}

        //1.驳回  只有要有驳回提交 状态 全部驳回  主表驳回
        $rs = model('useseal_audit')->where([ 'id' => $id , 'status' => ['<>' , -1]  , 'flag' => 2 ])->find();
        if( $rs ){
// dump('1.驳回');
            model('useseal_audit')->where(['id'=>$id , 'step' =>[ '>=' , $rs['step'] ]   ])->update(['status' => 2 ]); //未通过
            model('useseal')->where(['id'=> $id ])->update(['status' => -1 ]); //未通过
            return ;
        }
        // 2.找同意的
        $rs = model('useseal_audit')->where([ 'id' => $id , 'status' =>0 , 'flag' => 1 ])->find();
        if($rs){
// dump('2.找同意的');
            model('useseal_audit')->where(['id'=>$id , 'step'=>$rs['step'] ])->update(['status' => 1 ]); //未通过
        }
        // 3. next
        $rs = model('useseal_audit')->where([ 'id' => $id , 'status' =>0 ])->order('step asc')->find();
        if( !$rs ){
            $rs = model('useseal_audit')->where([ 'id' => $id , 'status' =>-1 ])->order('step asc')->find();
            if($rs){
// dump('next');
                model('useseal_audit')->where([ 'id' => $id ,'step'=>$rs['step'] ])->update(['status' => 0 ]); //未通过
            }else{
// dump('找不到 status = -1 ,说明已经全部审核通过，开始修改 useseal表 status = 2 通过');
                model('useseal')->where(['id'=> $id ])->update(['status' => 2 ]); //未通过

            }
        }


        


    }









    public function eqGetList($page,$pagesize,     $type_id , $apply_user_id , $equipment_id   ){
        $map = array();


        //$map['status']  = ['in',[2,3,4,5]];  

        if($type_id){
            $map['type_id']  = $type_id;  
        }
        if($apply_user_id){
            $map['apply_user_id']  = $apply_user_id; 
        }
        if($apply_user_id){
            $map['equipment_id']  = $equipment_id; 
        }

        $rs = $this->where($map)->order('id desc')->page($page,$pagesize)->select();
// echo $this->getLastSql();

        foreach($rs as $k => $v){
            $rs[$k]['status_text'] = $v['status_text'];
            $v['exp_time'];
            //$v->user;
            //$v->equipment;
            $v->seal;
            //$v->process;
            //$v->attachs;
            //$v->audits;
            //$v->logs;
            //unset($v->user['password']);
        }
        return $rs;





    }
    public function eqGetDetails($id){
        $map=array();
        $map['id'] = $id;
        $v = $this->find($id);
        if($v){
            $v['status_text'] = $v['status_text'];

            $v->user;
            $v->seal;
            $v->process;
            unset($v->user->password);
            return $v->toArray();  
        }else{
            return '没有找到数据';
        }
    }






}